﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EC_ASS.Models;
using Mvc.Mailer;
using EC_ASS.Mailers;

namespace EC_ASS.Controllers
{
    public class ProductController : Controller
    {
        private IUserMailer _userMailer = new UserMailer();
        public IUserMailer UserMailer
        {
            get { return _userMailer; }
            set { _userMailer = value; }
        }
        //
        // GET: /Product/

        public ActionResult Info(string id, string name)
        {
            DataECDataContext context = new DataECDataContext();
            var deals = context.Product_Deals.Where(tmp => tmp.ID.Equals(id));

            if (deals.Count() > 0)
            {
                return Redirect("/Deal/" + id + "/" + name + "/Info");
            }
            else
            {
                // Selected product
                Product product = context.Products.Single(p => p.ID == id);
                ViewBag.ProductDetail = product;
                // Detail images
                string[] imgList = product.Detail_Images.Split('_');
                ViewBag.ImgList = imgList;

                // Detail size
                string[] sizeList = product.Size.Split('_');
                ViewBag.Size = sizeList;

                //Load các sản phẩm cùng loại
                var listProduct = context.Products.Where(p => p.CatID == product.CatID);
                ViewBag.Name = name;
                return View(listProduct.ToList());
            }
        }

        public ActionResult Buy(string id, string ref_url)
        {
            DataECDataContext context = new DataECDataContext();
            Product product = context.Products.Single(tmp => tmp.ID == id);
            var deal = context.Product_Deals.Where(tmp => tmp.ID == id).ToList();
            ShopItem item = new ShopItem();
            item.cID = product.ID;
            item.cName = product.Name;
            item.cPicture = product.Picture;
            if (deal.Count() > 0)
            {
                // Get discount price
                item.cPrice = deal.ElementAt(0).Product.Price - (deal.ElementAt(0).Discount * deal.ElementAt(0).Product.Price) / 100;
            }
            else
            {
                item.cPrice = product.Price;
            }
            item.cQuantity = Int32.Parse(Request.Form.Get("Quantity"));
            item.cSize = Request.Form.Get("Size");
            if (Session["CART"] != null)
            {
                ShoppingCart cart = (ShoppingCart)Session["CART"];
                cart.AddItem(item);
                ViewBag.Total = cart.GetTotal();
                Session["CART"] = cart;
                return View(cart.Items);
            }
            else
            {
                ShoppingCart cart = new ShoppingCart();
                cart.AddItem(item);
                Session.Add("CART", cart);
                ViewBag.Total = cart.GetTotal();
                return View(cart.Items);
            }
        }

        // Module shopping cart
        public ActionResult _ShoppingCart()
        {
            ShoppingCart cart = new ShoppingCart();
            if (Session["CART"] != null)
            {
                cart = (ShoppingCart)Session["CART"];
            }
            ViewBag.Total = cart.GetTotal();
            return PartialView(cart.Items);
        }

        // Module update shopping cart
        public ActionResult _RemoveShoppingCartItem(ShopItem item)
        {
            ShoppingCart cart = new ShoppingCart();
            if (Session["CART"] != null)
            {
                cart = (ShoppingCart) Session["CART"];
                cart.RemoveItem(item);
            }
            ViewBag.Total = cart.GetTotal();
            return PartialView(cart.Items);
        }

        // Checkout
        [HttpGet]
        public ActionResult CheckOut()
        {
            if (Session["CUST"] == null)
            {
                return RedirectToAction("Login", "Account", new { ref_url = Request.RawUrl });
            }
            else
            {
                Customer customer = (Customer)Session["CUST"];
                ViewBag.CUST = customer;
                ShoppingCart cart = new ShoppingCart();
                if (Session["CART"] != null)
                {
                    cart = (ShoppingCart)Session["CART"];
                }
                ViewBag.Total = cart.GetTotal();
                return View(cart.Items);
            }
        }

        [HttpGet]
        public ActionResult _LoadShoppingCart()
        {
            Customer customer = (Customer)Session["CUST"];
            ViewBag.CUST = customer;
            ShoppingCart cart = new ShoppingCart();
            if (Session["CART"] != null)
            {
                cart = (ShoppingCart)Session["CART"];
            }
            ViewBag.Total = cart.GetTotal();
            return View(cart.Items);
        }

        [HttpPost]
        public ActionResult CheckOut(FormCollection form)
        {
            DataECDataContext context = new DataECDataContext();
            Order item = new Order();
            // Get cart
            ShoppingCart cart = (ShoppingCart) Session["CART"];

            // Get customer ID
            Customer customer = (Customer) Session["CUST"];
            item.CustomerID = customer.ID;

            // Get order time
            item.OrderDate = DateTime.Now;

            // Get buyer info
            item.Buyer = (string)form.Get("buyer");
            item.BuyerEmail = (string)form.Get("buyerEmail"); 
            item.BuyerPhone = (string)form.Get("buyerPhone"); 

            // Get receiver info
            item.Receiver= (string) form.Get("receiver");
            item.ShipPhone = (string) form.Get("shipContactPhone");
            item.ShipEmail = (string) form.Get("shipContactEmail");

            // Get home address if customers choose HCM area
            string home = (string)form.Get("homeAddress");

            // Set checked out status
            item.CheckedOut = false;

            // Get shipping address and shipping fee
            var addresses = GetAddress();
            if (!(String.IsNullOrEmpty(form.Get("shipAreaOther").ToString())))
            {
                // Get cart total price
                item.Total = cart.GetTotal();
                item.ShipFee = 40000;
                item.ShipAddress = form.Get("shipAreaOther").ToString();
            }
            else
            {
                string district = form.Get("shipAddress").ToString();
                foreach (var tmp in addresses)
                {
                    if (tmp.Code.Equals(district))
                    {
                        item.ShipAddress = home + ", " + tmp.Name;
                        item.Total = cart.GetTotal();
                        item.ShipFee = Int32.Parse(form.Get("shipFeeHCM").ToString());
                    }
                }
            }

            // Get payment method
            string method = form.Get("payment").ToString();
            if("nganluong".Equals(method)){
                item.PaymentMethod = "Thanh toán qua NganLuong.Vn";
            }
            else if ("onepay".Equals(method))
            {
                item.PaymentMethod = "Thanh toán qua OnePay";
            }
            else if ("ATM".Equals(method))
            {
                item.PaymentMethod = "Thanh toán qua ATM";
            }
            else
            {
                item.PaymentMethod = "Thanh toán sao khi nhận hàng";
            }

            // Save order
            context.Orders.InsertOnSubmit(item);
            context.SubmitChanges();

            // Get saved order ID
            int orderID = item.ID;

            foreach (ShopItem tmp in cart.Items)
            {
                // Save order detail info
                DetailOrder detailOrder = new DetailOrder();
                detailOrder.OrderID = orderID;
                detailOrder.ProductID = tmp.cID;
                detailOrder.Quantity = tmp.cQuantity;
                detailOrder.Price = tmp.cPrice * tmp.cQuantity;
                detailOrder.Size = tmp.cSize;
                context.DetailOrders.InsertOnSubmit(detailOrder);
                context.SubmitChanges();
            }

            // Remove shopping cart
            Session.Remove("CART");
            var OrderInfo = context.Orders.Single(tmp => tmp.ID == orderID);
            // Send email to customer
            UserMailer.OrderInfo(customer, OrderInfo).SendAsync();

            return RedirectToAction("OrderStatus", "Product", OrderInfo);
        }

        [HttpGet]
        public ActionResult OrderStatus(Order item)
        {
            return View(item);
        }

        protected List<ShipInternal> GetAddress()
        {
            List<ShipInternal> addresses = new List<ShipInternal>();
            addresses.Add(new ShipInternal("1", "Quận 1, TP Hồ Chí Minh"));
            addresses.Add(new ShipInternal("2", "Quận 3, TP Hồ Chí Minh"));
            addresses.Add(new ShipInternal("3", "Quận 5, TP Hồ Chí Minh"));
            addresses.Add(new ShipInternal("4", "Quận 7, TP Hồ Chí Minh"));
            addresses.Add(new ShipInternal("5", "Quận 9, TP Hồ Chí Minh"));
            addresses.Add(new ShipInternal("6", "Quận 10, TP Hồ Chí Minh"));
            addresses.Add(new ShipInternal("7", "Quận 12, TP Hồ Chí Minh"));
            addresses.Add(new ShipInternal("8", "Quận Tân Bình, TP Hồ Chí Minh"));
            addresses.Add(new ShipInternal("9", "Quận Bình Tân, TP Hồ Chí Minh"));
            addresses.Add(new ShipInternal("10", "Quận Tân Phú, TP Hồ Chí Minh"));
            addresses.Add(new ShipInternal("11", "Quận Thủ Đức, TP Hồ Chí Minh"));
            addresses.Add(new ShipInternal("12", "Quận Bình Chánh, TP Hồ Chí Minh"));
            return addresses;
        }
    }
}
